<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Operation;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Product\ProductClassify;
use App\Models\Operation\BATotal;
use App\Models\Product\ProductSku;
use App\Models\Operation\ProfitSku;
use App\Models\SalesAmazon\SalesAmountDay;
use App\Models\SalesAmazon\SalesVolumeDay;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class TotalAjax {

    public function verifyTotalProfit($id)
    {
        $baTotal = BATotal::query()->find($id);
        $date = $baTotal->report_date;
        $_date = date("Ymd",strtotime($date));
        $countryId = $baTotal->country_id;
        $classifyId = $baTotal->classify_id;
        $spend = $baTotal->spend;
        $reimburse = $baTotal->reimburse;
        $pSkuIds = ProductSku::query()
            ->where('classify_id',$classifyId)
            ->pluck('id')
            ->toArray();
        $_promotionDiscount = SalesAmountDay::query()
            ->where('day',$_date)
            ->where('country_id',$countryId)
            ->whereIn('psku_id',$pSkuIds)
            ->sum('promotion_discount');
        $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($countryId);
        $rateOdds = ExchangeRate::getRateOddsToRMB($currencyCode,strtotime($date));
        $promotionDiscount = round($_promotionDiscount * $rateOdds,3);
        $basics = [];
        $basics['date'] = $date;
        $basics['country'] = SysCountry::getCountryById($countryId);
        $basics['title'] = ProductClassify::getTitleById($classifyId);
        $basics['rateOdds'] = $rateOdds;
        $amounts = SalesAmountDay::query()
            ->where('day',$_date)
            ->where('country_id',$countryId)
            ->whereIn('psku_id',$pSkuIds)
            ->select(DB::raw('sum(amount) as amount,psku_id'))
            ->groupBy('psku_id')
            ->get();
        $profit = 0;
        $prs = [];
        foreach ($amounts as $amount){
            $item = ProfitSku::query()
                ->where('psku_id',$amount->psku_id)
                ->where('country_id',$countryId)
                ->where('transport',1)
                ->first();
            $temp = [];
            $temp['psku_code'] = ProductSku::getValueById($amount->psku_id,'psku_code');
            $temp['amount'] = $amount->amount;
            if($item){
                $temp['tpye'] = 'TRUE';
                $volume = SalesVolumeDay::query()
                    ->where('day',$_date)
                    ->where('country_id',$countryId)
                    ->where('psku_id',$amount->psku_id)
                    ->sum('volume');
                $tpl = round($volume * $item->tpl_rmb / $item->rate_odds,3);
                $headCost = $volume * $item->head_cost;
                $fbaFee = $volume * $item->fba_fee;
                $cost = ProfitSku::getCost($tpl,$amount->amount,$headCost,$fbaFee,$item->commission,$item->return,$item->vat);
                $temp['volume'] = $volume;
                $temp['tpl'] = $tpl;
                $temp['head_cost'] = $headCost;
                $temp['fba_fee'] = $fbaFee;
                $temp['commission'] = $item->commission;
                $temp['return'] = $item->return;
                $temp['vat'] = $item->vat;
                $temp['cost'] = $cost;
            }else{
                $temp['tpye'] = 'FALSE';
                $temp['cost'] = 0;
                $cost = 0;
            }
            $temp['profit'] = round(($amount->amount - $cost),3);
            $_profit = round(($amount->amount - $cost),3) * $rateOdds;
            $temp['profit_rmb'] = $_profit;
            $profit += $_profit;
            $prs[$amount->psku_id] = $temp;
        }
        $pt = round($profit - $spend - $reimburse - $promotionDiscount,3);
        return view('operation.total.profit-modal', compact('basics','prs','profit','spend','reimburse','promotionDiscount','pt'));
    }

    public function verifyTotalProfitNew($id)
    {
        $baTotal = BATotal::query()->find($id);
        $date = $baTotal->report_date;
        $_date = date("Ymd",strtotime($date));
        $countryId = $baTotal->country_id;
        $classifyId = $baTotal->classify_id;
        $spend = $baTotal->spend;
        $reimburse = $baTotal->reimburse;
        $pSkuIds = ProductSku::query()
            ->where('classify_id',$classifyId)
            ->pluck('id')
            ->toArray();
        $_promotionDiscount = SalesAmountDay::query()
            ->where('day',$_date)
            ->where('country_id',$countryId)
            ->whereIn('psku_id',$pSkuIds)
            ->sum('promotion_discount');
        $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($countryId);
        $rateOdds = ExchangeRate::getRateOddsToRMB($currencyCode,strtotime($date));
        $promotionDiscount = round($_promotionDiscount * $rateOdds,3);
        $basics = [];
        $basics['date'] = $date;
        $basics['country'] = SysCountry::getCountryById($countryId);
        $basics['title'] = ProductClassify::getTitleById($classifyId);
        $basics['rateOdds'] = $rateOdds;
        $amounts = SalesAmountDay::query()
            ->where('day',$_date)
            ->where('country_id',$countryId)
            ->whereIn('psku_id',$pSkuIds)
            ->select(DB::raw('sum(amount) as amount,psku_id'))
            ->groupBy('psku_id')
            ->get();
        $profit = 0;
        $prs = [];
        foreach ($amounts as $amount){
            $item = ProfitSku::query()
                ->where('psku_id',$amount->psku_id)
                ->where('country_id',$countryId)
                ->where('transport',1)
                ->first();
            $temp = [];
            $temp['psku_code'] = ProductSku::getValueById($amount->psku_id,'psku_code');
            $temp['amount'] = $amount->amount;
            if($item){
                $temp['tpye'] = 'TRUE';
                $volume = SalesVolumeDay::query()
                    ->where('day',$_date)
                    ->where('country_id',$countryId)
                    ->where('psku_id',$amount->psku_id)
                    ->sum('volume');
                $tpl = round($volume * $item->tpl_rmb / $item->rate_odds,3);
                $headCost = $volume * $item->head_cost;
                $fbaFee = $volume * $item->fba_fee;
                $cost = ProfitSku::getCost($tpl,$amount->amount,$headCost,$fbaFee,$item->commission,$item->return,$item->vat);
                $temp['volume'] = $volume;
                $temp['tpl'] = $tpl;
                $temp['head_cost'] = $headCost;
                $temp['fba_fee'] = $fbaFee;
                $temp['commission'] = $item->commission;
                $temp['return'] = $item->return;
                $temp['vat'] = $item->vat;
                $temp['cost'] = $cost;
            }else{
                $temp['tpye'] = 'FALSE';
                $temp['cost'] = 0;
                $cost = 0;
            }
            $temp['profit'] = round(($amount->amount - $cost),3);
            $_profit = round(($amount->amount - $cost),3) * $rateOdds;
            $temp['profit_rmb'] = $_profit;
            $profit += $_profit;
            $prs[$amount->psku_id] = $temp;
        }
        $pt = round($profit - $spend - $reimburse - $promotionDiscount,3);
        return view('operation.total.profit-modal-new', compact('basics','prs','profit','spend','reimburse','promotionDiscount','pt'));
    }

    public function toCheck(){
        return view('operation.total.check-modal');
    }

    public function checkTotal($reportDate)
    {
        if(!$reportDate){
            return response()->json(['status' =>false, 'message' => '操作失败！']);
        }
        if(strtotime($reportDate) > strtotime('-3 days')){
            $max = date('Y-m-d',strtotime('-3 days'));
            return response()->json(['status' =>false, 'message' => "核算日期最大为：{$max}！"]);
        }
        $day = getDayDiffByDateStr($reportDate,date('Y-m-d'));
        Artisan::call('check:operation-total',['day' => $day]);
        return response()->json(['status' =>true, 'message' => '操作成功！']);
    }

    public function toStar(){
        return view('operation.total.star-modal');
    }

    public function starTotal($reportDate)
    {
        if(!$reportDate){
            return response()->json(['status' =>false, 'message' => '操作失败！']);
        }
        if(strtotime($reportDate) > strtotime('-3 days')){
            $max = date('Y-m-d',strtotime('-3 days'));
            return response()->json(['status' =>false, 'message' => "更新日期最大为：{$max}！"]);
        }
        $day = getDayDiffByDateStr($reportDate,date('Y-m-d'));
        Artisan::call('operation:total-star',['day' => $day]);
        return response()->json(['status' =>true, 'message' => '操作成功！']);
    }

}
